package com.jingdianjichi.auth.application.interceptor;


import com.jingdianjichi.auth.application.context.LoginContextHolder;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 微服务自己的登录拦截器，从gateway层处理后的请求包中，拿到用户id
 *              并解析到ThreadLocal里面
 * @return:
 * @Author:  sky
 * @date:  2024/11/23 23:08
 */
public class LoginInterceptor implements HandlerInterceptor {

    // 在访问真实服务之前，从请求中拿到用户id，并进行封装
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginId = request.getHeader("loginId");
        LoginContextHolder.set("loginId", loginId);

        return true;
    }

    // 在服务处理完毕之后，及时销毁封装的threadLocal，避免堆内存泄漏（弱引用的问题）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LoginContextHolder.remove();
    }

}
